<template>
  <div class="login-container">
    <!-- 左侧图片区域 -->
    <div class="login-image">
      <img src="@/assets/logo.png" alt="Login Image" />
    </div>

    <!-- 右侧登录框 -->
    <div class="login-box">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="username"
            required
            class="input-field"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="password"
            required
            class="input-field"
          />
        </div>

        <!-- 用户协议勾选框 -->
        <div class="form-group">
          <label>
            <input
              type="checkbox"
              v-model="agreeToTerms"
              class="checkbox"
            />
            我同意 <a href="#" class="terms-link">用户协议</a>
          </label>
          <span v-if="termsError" class="error-text">{{ termsError }}</span>
        </div>

        <div v-if="error" class="error">{{ error }}</div>

        <button type="submit" class="login-button" :disabled="!agreeToTerms">登录</button>
      </form>
    </div>
    
    <!-- 虚拟过渡效果 -->
    <div class="virtual-transition"></div>
  </div>
</template>

<script>
import axios from "@/utils/axios";
import { setToken } from "@/utils/auth"; // 导入存储 token 的方法

export default {
  name: "userLogin",
  data() {
    return {
      username: "",
      password: "",
      error: "",
      agreeToTerms: false,  // 记录用户是否同意协议
      termsError: "",  // 用户协议错误提示
    };
  },
  mounted() {
    // 引入 layui CSS
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '//unpkg.com/layui@2.10.1/dist/css/layui.css';
    document.head.appendChild(link);

    // 引入 layui JS
    const script = document.createElement('script');
    script.src = '//unpkg.com/layui@2.10.1/dist/layui.js';
    document.body.appendChild(script);
  },
  methods: {
    async handleLogin() {
      if (!this.agreeToTerms) {
        this.termsError = "您必须同意用户协议才能登录";
        return;
      }

      try {
        const response = await axios.post("/login", {
          username: this.username,
          password: this.password,
        });
        const token = response.data.token;
        const role = response.data.role;
        setToken(token, role);
        
        // 获取当前时间
        const now = new Date();
        const hours = now.getHours();
        let timeGreeting = '';
        
        if (hours >= 5 && hours < 12) {
          timeGreeting = '早上好';
        } else if (hours >= 12 && hours < 14) {
          timeGreeting = '中午好';
        } else if (hours >= 14 && hours < 18) {
          timeGreeting = '下午好';
        } else {
          timeGreeting = '晚上好';
        }

        const dateStr = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
        
        // 使用 layui 显示欢迎信息
        window.layui.use(['layer'], () => {
          const layer = window.layui.layer;
          layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: ['600px', 'auto'],
            shade: 0.8,
            id: 'LAY_welcomeMsg',
            btn: ['开启我的旅程'],
            btnAlign: 'c',
            moveType: 1,
            content: `
              <div style="padding: 30px; line-height: 22px; background-color: #f0f9eb; color: #333; font-family: 'Microsoft YaHei', sans-serif;">
                <div style="text-align: center; margin-bottom: 20px;">
                  <h3 style="font-size: 24px; color: #409EFF; margin-bottom: 15px;">${timeGreeting}，${this.username}</h3>
                  <p style="color: #666; font-size: 14px; margin-bottom: 20px;">今天是 ${dateStr}</p>
                </div>
                <div style="text-align: justify; font-size: 15px; color: #606266; line-height: 1.8; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);">
                  <p style="text-indent: 2em; margin-bottom: 15px;">愿你的人生如星辰般璀璨，前途无可限量，梦想成真，未来充满阳光与希望。</p>
                  <p style="text-indent: 2em; margin-bottom: 15px;">愿你勇敢追梦，每一步都走得坚定有力，披荆斩棘，乘风破浪。</p>
                  <p style="text-indent: 2em; margin-bottom: 15px;">前方的路光明而广阔，愿你心怀梦想，眼里有光，脚下有路，未来无限辉煌。</p>
                  <p style="text-indent: 2em;">愿你未来的每一天都充满力量与温暖，成就自己的精彩人生。</p>
                </div>
              </div>
            `,
            success: function(layero){
              const btn = layero.find('.layui-layer-btn0');
              btn.css({
                'background-color': '#409EFF',
                'color': '#fff',
                'border-radius': '20px',
                'padding': '8px 30px',
                'font-size': '16px',
                'border': 'none'
              });
            },
            yes: (index) => {
              // 先关闭当前弹出层
              layer.close(index);
              // 使用 nextTick 确保 DOM 更新完成
              this.$nextTick(() => {
                // 跳转到首页
                this.$router.push({ name: "Home" }).then(() => {
                  // 跳转完成后刷新页面
                  window.location.reload();
                });
              });
            }
          });
        });
      } catch (err) {
        this.error = err.response.data.error || "登录失败，请重试";
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  background: #f7f8fa;
}

/* 左侧图片 */
.login-image {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #e9ecef;
}

.login-image img {
  width: 80%;
  max-width: 600px;
  height: auto;
}

/* 右侧登录框 */
.login-box {
  width: 400px;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin: auto;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.login-form .form-group {
  margin-bottom: 15px;
}

.login-form label {
  display: block;
  margin-bottom: 5px;
  color: #555;
}

.input-field {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.input-field:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 3px rgba(0, 123, 255, 0.5);
}

.error {
  color: #ff4d4f;
  font-size: 14px;
  margin-bottom: 15px;
  text-align: center;
}

.login-button {
  width: 100%;
  padding: 10px;
  background: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}

.login-button:hover {
  background: #0056b3;
}

.login-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.checkbox {
  margin-right: 10px;
}

.terms-link {
  color: #007bff;
}

.terms-link:hover {
  text-decoration: underline;
}

.error-text {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 5px;
}

/* 虚拟过渡效果 */
.virtual-transition {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.1), rgba(255, 255, 255, 0));
  animation: fadeUp 3s ease-out infinite;
}

@keyframes fadeUp {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</style>
